package com.yupi.yupicturespringboot.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yupi.yupicturespringboot.config.CosClientConfig;
import com.yupi.yupicturespringboot.exception.BusinessException;
import com.yupi.yupicturespringboot.exception.ErrorCode;
import com.yupi.yupicturespringboot.manager.CosManager;
import com.yupi.yupicturespringboot.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;


/**
 * 图片上传模板
 */
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传图片
     *
     * @param inputSource      图片文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 上传图片
        validPicture(inputSource);
        //图片上传路径
        String uuid = RandomUtil.randomString(16);
        String originalFilename = getOriginalFilename(inputSource);
        //自己拼接文件上传路径，而不是使用原始文件名称可以添加安全性
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        //解析结果并返回
        File file1 = null;
        try {
            file1 = File.createTempFile(uploadFilePath, null);
            //处理文件来源
            processFile(inputSource, file1);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file1);
            //获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //获取到图片信息对象
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)) {
                //获取到压缩后的图片对象
                CIObject compressedCiObject = objectList.get(0);

                CIObject thumbnailCiObject = compressedCiObject;
                //生成了缩略图才获取
                if (objectList.size() > 1) {
                    thumbnailCiObject = objectList.get(1);
                }

                //封装压缩图的返回结果
                return buildResult(originalFilename, compressedCiObject, thumbnailCiObject);
            }

            //封装返回结果

            return buildResult(imageInfo, uploadFilePath, originalFilename, file1);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            //清理临时文件
            this.deleteTempFile(file1);
        }


    }


    /**
     * 封装返回结果,构造返回对象 ，压缩后
     *
     * @param originalFilename
     * @param compressedCiObject 压缩后的图片对象
     * @param thumbnailCiObject  缩略图对象
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject compressedCiObject, CIObject thumbnailCiObject) {
        //计算宽和高
        int pictureWidth = compressedCiObject.getWidth();
        int pictureHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(pictureWidth * 1.0 / pictureHeight, 2).doubleValue();


        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(pictureWidth);
        uploadPictureResult.setPicHeight(pictureHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        //设置缩略图
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());


        //返回访问的地址
        return uploadPictureResult;
    }

    /**
     * 封装返回结果,构造返回对象
     *
     * @param imageInfo        图片信息对象
     * @param uploadFilePath   上传路径
     * @param originalFilename 原始文件名
     * @param file1            临时文件
     * @return
     */
    private UploadPictureResult buildResult(ImageInfo imageInfo, String uploadFilePath, String originalFilename, File file1) {
        //计算宽和高
        int pictureWidth = imageInfo.getWidth();
        int pictureHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(pictureWidth * 1.0 / pictureHeight, 2).doubleValue();


        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file1));
        uploadPictureResult.setPicWidth(pictureWidth);
        uploadPictureResult.setPicHeight(pictureHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());


        //返回访问的地址
        return uploadPictureResult;
    }

    /**
     * 处理输入源生成本地临时文件
     *
     * @param inputSource
     * @param file
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 获取原始文件名
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSource);

    /**
     * 校验输入源（本地文件或 url）
     *
     * @param inputSource
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 删除临时文件
     *
     * @param file1
     */
    public void deleteTempFile(File file1) {
        if (file1 != null) {
            boolean delete = file1.delete();
            if (!delete) {
                log.error("文件删除失败,filepath:{}", file1.getAbsolutePath());
            }

        }
    }


}
